from django.shortcuts import render, redirect
from django.urls import reverse
from django.views import View
from django import http
import re
from django.db import DatabaseError
from django.contrib.auth import login, mixins, logout, authenticate
from django_redis import get_redis_connection

from .models import User
from mall_30.utils.response_code import RETCODE

# Create your views here.


# 注册
class RegisterView(View):
    """返回注册界面"""
    def get(self, request):
        return render(request, 'register.html')

    # 接受请求,获取信息
    def post(self, request):

        username = request.POST.get('username')
        password = request.POST.get('password')
        password2 = request.POST.get('password2')
        mobile = request.POST.get('mobile')
        sms_code = request.POST.get('sms_code')
        allow = request.POST.get('allow')

        # 校验
        if not all([username, password, password2,mobile, sms_code]):
            return http.HttpResponseForbidden('缺少必要的参数')

        if re.match(r'^[a-zA-Z0-9_-]{5,20}$', username) is False:
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')

        if re.match(r'^[0-9A-Za-z]{8,20}$', password) is False:
            return http.HttpResponseForbidden('请输入8-20个字符的用户名')

        if password != password2:
            return http.HttpResponseForbidden('两次输入的密码不一致')

        if re.match(r'^1[3456789]\d{9}$', mobile) is False:
            return http.HttpResponseForbidden('您输入的手机号格式不正确')

        if allow != 'on':
            return http.HttpResponseForbidden('请签订协议')

        #  短信验证
        redis_conn = get_redis_connection('verify_code')

        sms_code_redis = redis_conn.get('sms_code_%s'%mobile)
        if sms_code_redis.decode() != sms_code:
            return http.HttpResponseForbidden('短信验证码错误')

        # 创建用户
        try:
            user = User.objects.create_user(username=username, password=password, mobile= mobile)

        except DatabaseError:
            return http.HttpResponseForbidden('用户注册失败')

        # 状态保持
        login(request, user)

        # 响应结果重定向到首页
        response = redirect('/')
        response.set_cookie('username', user.username, 300)
        return response


class UsernameCountView(View):
    """判断用户名是否重名"""

    def get(self, request, username):

        #获取参数
        count = User.objects.filter(username=username).count()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class MobileCountView(View):
    """判断手机号是否重名"""

    def get(self, request, mobile):

        count = User.objects.filter(mobile=mobile).count()

        return http.JsonResponse({'code': RETCODE.OK, 'errmsg': 'OK', 'count': count})


class LoginView(View):
    """登录界面"""

    def get(self, request):
        return render(request, 'login.html')

    # 接受请求,获取信息
    def post(self, request):

        username = request.POST.get('username')
        password = request.POST.get('password')
        remembered = request.POST.get('remembered')

        # 校验
        if not all([username, password]):
            return http.HttpResponseForbidden('缺少必要的参数')

        if re.match(r'^[a-zA-Z0-9_-]{5,20}$', username) is False:
            return http.HttpResponseForbidden('请输入5-20个字符的用户名')

        if re.match(r'^[0-9A-Za-z]{8,20}$', password) is False:
            return http.HttpResponseForbidden('请输入8-20个字符的用户名')

        # 登录认证
        user = authenticate(username=username, password=password)

        if user is None:
            return render(request, 'login.html', {'account_errmsg': '用户名或者密码错误'})

        # remembered
        if remembered != 'on':
            request.session.set_expiry(0)
        else:
            request.session.set_expiry(None)

        # 状态保持
        login(request, user)

        # 响应
        response = redirect(request.GET.get('next', '/'))

        response.set_cookie('username', user.username, 300)

        return response


class LogoutView(View):
    """退出登录"""

    def get(self, request):
        # 清除session中的状态保持数据

        logout(request)

        response = redirect(reverse('users:login'))
        response.delete_cookie('username')
        return response



class UserInfoView(mixins.LoginRequiredMixin,View):
    """用户中心"""

    def get(self, request):

        return render(request, 'user_center_info.html')
















